package com.zhang.sql;

import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.Tumble;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.types.Row;

import static org.apache.flink.table.api.Expressions.$;
import static org.apache.flink.table.api.Expressions.lit;

/**
 * @title: 滚动窗口，基于处理时间
 * @author: zhang
 * @date: 2022/2/13 21:34
 */
public class GroupWindowTumblingProcessTimeTableApi {
    public static void main(String[] args) throws Exception {
        //获取执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env);

        SingleOutputStreamOperator<Tuple2<String, Integer>> streamOperator = env
                .socketTextStream("localhost", 9999)
                .map(new MapFunction<String, Tuple2<String, Integer>>() {
                    @Override
                    public Tuple2<String, Integer> map(String value) throws Exception {
                        String[] fields = value.split(" ");
                        return Tuple2.of(
                                fields[0], Integer.parseInt(fields[1])
                        );
                    }
                });

        Table table = tableEnv.fromDataStream(streamOperator,
                $("word"),
                $("count"),
                $("pt").proctime());

        Table result = table.window(Tumble.over(lit(5).second()).on($("pt")).as($("w")))
                .groupBy($("word"), $("w"))
                .select($("word"), $("count").sum());

        tableEnv.toAppendStream(result, Row.class).print();

        //执行任务
        env.execute();
    }
}
